import { useState } from 'react'
import { Form, Input, Button, Card, message, Tabs } from 'antd'
import { UserOutlined, LockOutlined, MailOutlined, PhoneOutlined } from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import { useAuthStore } from '../store/auth'

export default function Login() {
  const [loading, setLoading] = useState(false)
  const navigate = useNavigate()
  const { login, register } = useAuthStore()

  const handleLogin = async (values: any) => {
    setLoading(true)
    try {
      await login(values.username, values.password)
      message.success('登录成功')
      navigate('/')
    } catch (error: any) {
      message.error(error || '登录失败，请检查用户名和密码')
    } finally {
      setLoading(false)
    }
  }

  const handleRegister = async (values: any) => {
    setLoading(true)
    try {
      const { confirmPassword, ...userData } = values
      await register(userData)
      message.success('注册成功')
      navigate('/')
    } catch (error: any) {
      message.error(error || '注册失败，请重试')
    } finally {
      setLoading(false)
    }
  }

  const loginFormItems = [
    {
      name: 'username',
      label: '用户名',
      rules: [{ required: true, message: '请输入用户名' }],
      children: <Input prefix={<UserOutlined />} placeholder="请输入用户名" />,
    },
    {
      name: 'password',
      label: '密码',
      rules: [{ required: true, message: '请输入密码' }],
      children: <Input.Password prefix={<LockOutlined />} placeholder="请输入密码" />,
    },
  ]

  const registerFormItems = [
    {
      name: 'username',
      label: '用户名',
      rules: [{ required: true, message: '请输入用户名' }],
      children: <Input prefix={<UserOutlined />} placeholder="请输入用户名" />,
    },
    {
      name: 'password',
      label: '密码',
      rules: [{ required: true, message: '请输入密码' }],
      children: <Input.Password prefix={<LockOutlined />} placeholder="请输入密码" />,
    },
    {
      name: 'confirmPassword',
      label: '确认密码',
      dependencies: ['password'],
      rules: [
        { required: true, message: '请确认密码' },
        ({ getFieldValue }: { getFieldValue: (key: string) => any }) => ({
          validator(_: any, value: string) {
            if (!value || getFieldValue('password') === value) {
              return Promise.resolve()
            }
            return Promise.reject(new Error('两次输入的密码不一致'))
          },
        }),
      ],
      children: <Input.Password prefix={<LockOutlined />} placeholder="请确认密码" />,
    },
    {
      name: 'email',
      label: '邮箱',
      rules: [{ type: 'email', message: '请输入有效的邮箱地址' }],
      children: <Input prefix={<MailOutlined />} placeholder="请输入邮箱（可选）" />,
    },
    {
      name: 'phone',
      label: '手机号',
      rules: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }],
      children: <Input prefix={<PhoneOutlined />} placeholder="请输入手机号（可选）" />,
    },
  ]

  const tabItems = [
    {
      key: 'login',
      label: '登录',
      children: (
        <Form
          name="login"
          onFinish={handleLogin}
          autoComplete="off"
          size="large"
        >
          {(loginFormItems as any[]).map((item) => (
            <Form.Item key={item.name} {...item as any}>
              {item.children}
            </Form.Item>
          ))}
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      ),
    },
    {
      key: 'register',
      label: '注册',
      children: (
        <Form
          name="register"
          onFinish={handleRegister}
          autoComplete="off"
          size="large"
        >
          {(registerFormItems as any[]).map((item) => (
            <Form.Item key={item.name} {...item as any}>
              {item.children}
            </Form.Item>
          ))}
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
            >
              注册
            </Button>
          </Form.Item>
        </Form>
      ),
    },
  ]

  return (
    <div style={{
      minHeight: '100vh',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      padding: '16px'
    }}>
      <Card
        title={
          <div style={{ textAlign: 'center', fontSize: '24px', fontWeight: 'bold' }}>
            家族族谱管理系统
          </div>
        }
        style={{ width: '100%', maxWidth: 400 }}
      >
        <Tabs
          items={tabItems}
          centered
          size="large"
        />
      </Card>
    </div>
  )
}